import Vue from "vue";
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from "./App.vue";
import router from "./router";
import axios from "axios";

const $axios = axios.create({
  baseURL: 'http://localhost:8000/',
  headers: { 'X-Requested-With': 'XMLHttpRequest' },
  // `withCredentials` 表示跨域请求时是否需要使用凭证(即是否支持session)
  withCredentials: true
});

Vue.prototype.$axios = $axios;

Vue.prototype.$ajax = function (getAxiosPromise, hasLoading) {

  let promise = new Promise((resolve) => {

    try {
      let loading;
      //显示加载提示代码
      if (hasLoading) {
        loading = this.$loading({
          lock: true,
          background: 'rgba(150, 150, 150, 0.3)'
        });
      }

      getAxiosPromise()
        .then(res => {//处理成功响应

          //关闭加载提示
          if (hasLoading) {
            loading.close();
          }

          let result = res.data;//获取服务器的响应结果

          
          if (!result.logined && result.logined === undefined ) {
            //服务器响应数据无已登录标志属性logined
           
            resolve(result);//由then方法的参数（一个函数）继续处理响应结果
            return;
          }
         
          if (!result.logined) {
            //服务器响应结果的已登录标志属性logined的值为false

            this.$message({
              message: '您已下线，请登录！',
              type: 'warning',
              onClose() {
                window.top.location.href = 'index.html';
              }
            });

            return;
          }

          if(!result.authorized){
            this.$message({
              message: '您的权限不足！',
              type: 'error'
            });

            return;
          }

          //由then方法的参数（一个函数）继续处理响应结果
          resolve(result);

        })
        .catch(err => {//处理错误响应

          //关闭加载提示
          if (hasLoading) {
            loading.close();
          }

          console.log(err);//控制台打印错误信息

          //若服务器没有响应
          if (err.request.status == 0) {
            this.$message({
              message: `地址 ${err.config.url} 没有响应，可能服务器不可用或者地址不正确。`,
              type: 'error'
            });
            return;
          }

          //若错误对象不存在response属性或者该属性值可转换为false
          if (!err.response) {

            this.$message({
              message: '错误: ' + err.message,
              type: 'error'
            });

            return;
          }

          this.$message({
            message: `响应错误：${err.response.status}`,
            type: 'error'
          });

        });

    } catch (error) {//发生异常

      console.log(error);

      this.$message({
        message: '错误:' + error.message,
        type: 'error'
      });

      throw error;

    }

  });

  return promise;

};


Vue.prototype.$myoprate = function (getAxiosPromise, confirmInfo) {

  let promise = new Promise((resolve) => {

    if (confirmInfo && confirmInfo.message && confirmInfo.title) {

      this.$confirm(confirmInfo.message, confirmInfo.title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.$ajax(getAxiosPromise, true)
          .then((result) => {

            if (result.success) {


              if (confirmInfo && confirmInfo.postMsg) {//是否提示后执行函数

                this.$message({
                  message: result.message,
                  type: 'success',
                  duration: (confirmInfo && confirmInfo.duration && !isNaN(confirmInfo.duration)) ? parseInt(confirmInfo.duration) : 1500,
                  onClose: function () {
                    resolve(result);
                  }
                });

              } else {

                this.$message({
                  message: result.message,
                  type: 'success',
                  duration: (confirmInfo && confirmInfo.duration && !isNaN(confirmInfo.duration)) ? parseInt(confirmInfo.duration) : 1500
                });
                resolve(result);

              }

            } else {

              this.$alert(result.message, '错误', {
                confirmButtonText: '确定',
                type: 'error'
              });

            }

          });

      }).catch(() => {
        this.$message({
          message: '您已取消操作！',
          type: 'info'
        });
      });

    } else {


      this.$ajax(getAxiosPromise, true)
        .then((result) => {

          if (result.success) {

            if (confirmInfo && confirmInfo.postMsg) {//是否提示后执行函数

              this.$message({
                message: result.message,
                type: 'success',
                duration: (confirmInfo && confirmInfo.duration && !isNaN(confirmInfo.duration)) ? parseInt(confirmInfo.duration) : 1500,
                onClose: function () {
                  resolve(result);
                }
              });


            } else {
              this.$message({
                message: result.message,
                type: 'success',
                duration: (confirmInfo && confirmInfo.duration && !isNaN(confirmInfo.duration)) ? parseInt(confirmInfo.duration) : 1500
              });
              resolve(result);
            }



          } else {

            this.$alert(result.message, '错误', {
              confirmButtonText: '确定',
              type: 'error'
            });

          }

        });


    }

  });

  return promise;

};

Vue.prototype.$myGet = function (url, config) {

  let promise = new Promise((resolve) => {

    this.$ajax(() => $axios.get(url, config), config?config.hasLoading:false)
      .then((result) => {
        resolve(result);
      });

  });

  return promise;
};

Vue.prototype.$myPost = function (url, data, config) {

  return this.$myoprate(() => { return $axios.post(url, data, config); }, config);

};

Vue.prototype.$myPut = function (url, data, config) {

  return this.$myoprate(() => { return $axios.put(url, data, config); }, config);

};

Vue.prototype.$myDelete = function (url, config) {

  return this.$myoprate(() => { return $axios.delete(url, config); }, config);

};


Vue.prototype.$myLogined = function () {

  return this.$myGet('/pub/currUser');

};

/*
给Vue添加原型方法，以application/x-www-form-urlencoded编码格式，向服务器发出post请求，返回promise，
then方法的参数是一个函数，该函数的参数为服务器发送的未经包装响应数据
*/
Vue.prototype.$post = function (url, data, config) {
  if (!config) {
    config = {};
  }

  if (!config.headers) {
    config.headers = { "Content-Type": 'application/x-www-form-urlencoded' };
  } else {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  }

  config.transformRequest = [function (data) {

    if (!data || typeof (data) === 'string') {
      return data;
    }

    if (!(typeof (data) === 'object')) {
      return data;
    }


    let params = [];
    for (let prop in data) {
      if (data[prop] instanceof Array) {
        let arr = data[prop];
        for (let i = 0; i < arr.length; i++) {
          params.push(prop + "=" + arr[i]);
        }
      } else {
        params.push(prop + "=" + data[prop]);
      }

    }
    return params.join("&");

  }];

  return this.$myoprate(() => { return $axios.post(url, data, config); }, config);

};

/*
给Vue添加原型方法 向服务器发出get请求，返回promise，
then方法的参数是一个函数，该函数的参数为服务器发送的未经包装响应数据
*/
Vue.prototype.$get = function (url, data, config) {

  if (!config) {
    config = {};
  }

  config.params = data;

  return this.$myGet(url, config);

}



Vue.use(ElementUI);

Vue.config.productionTip = false;

new Vue({
  router,
  render: h => h(App)
}).$mount("#app");
